package gateway

import (
	"cowb/log"
	"cowb/rpcpool"
	"cowb/util"
	"encoding/json"
	"io/ioutil"
	"net/http"

	"github.com/gin-gonic/gin"
)

func init() {
	gin.SetMode(gin.ReleaseMode)
}

type gwhttp struct {
}

func (this *gwhttp) Run(host string) {
	log.Info("gateway http host:%s", host)

	r := gin.Default()

	r.POST("/token", func(c *gin.Context) {
		sid, err := util.UniqueID()
		if err != nil {
			c.String(http.StatusInternalServerError, "内部错误")
			return
		}
		setSession(sid)
		c.String(http.StatusOK, sid)
	})

	r.POST("/", func(c *gin.Context) {
		city := getRemoteCity(c.Request.RemoteAddr)
		if !isWhiteCity(city) {
			c.String(http.StatusBadRequest, "禁止访问")
			return
		}

		body, err := ioutil.ReadAll(c.Request.Body)
		if err != nil {
			log.Error("%v", err)
			return
		}
		defer c.Request.Body.Close()

		m := &ClientMsg{}
		err = json.Unmarshal(body, m)
		if err != nil {
			log.Error("%v", err)
			c.String(http.StatusBadRequest, err.Error())
			return
		}

		if !checkSession(m.SID) {
			c.String(http.StatusBadRequest, "无效的会话")
			return
		}

		setSession(m.SID)

		param, err := json.Marshal(m.Body)
		if err != nil {
			log.Error("%v", err)
			c.String(http.StatusInternalServerError, "内部错误")
			return
		}

		relay, err := rpcpool.Call(m.Cmd, param)
		if err != nil {
			log.Error("%v", err)
			c.String(http.StatusInternalServerError, "内部错误")
			return
		}
		c.Status(http.StatusOK)
		_, err = c.Writer.Write(relay)
		if err != nil {
			log.Error("%v", err)
			c.String(http.StatusInternalServerError, "内部错误")
			return
		}
	})

	r.Run(host)
}
